<template>
  <div class="i_bg">  
    <div class="content mar_20">
    	<img src="../../../assets/images/img1.jpg" />        
    </div>
    
    <!--Begin 第一步：查看购物车 Begin -->
    <div class="content mar_20">
    	<table border="0" class="car_tab" style="width:1200px; margin-bottom:50px;" cellspacing="0" cellpadding="0">
          <tr>
            <td class="car_th" width="190">全选<input type="checkbox" v-model="allChecked" @click="selectAll"></td>
            <td class="car_th" width="190">商品名称</td>
            <td class="car_th" width="140">描述</td>
            <td class="car_th" width="150">购买数量</td>
            <td class="car_th" width="130">小计</td>
            <td class="car_th" width="150">操作</td>
          </tr>
          <tr class="car_tr" v-for="(item,index) in cartList" :key="item.id">
            <td align="center">
                <input type="checkbox" v-model="statusArr[index]" @click="selectOne(index)">
            </td>
            <td>
            	<div class="c_s_img"><img :src="'http://192.168.79.98:9001/'+item.fileName" width="73" height="73" /></div>
                {{ item.name }}
            </td>
            <td align="center">{{ item.description }}</td>
            <td align="center">
            	<div class="c_num">
                    <input type="button" value="" @click="reduceCount(item.count,item.id,index)"  class="car_btn_1" />
                	<input type="text" v-model.number="item.count"  name="" class="car_ipt" @focus="cacheOldCount(item.count, index)" @blur="checkNum(item.id, index)" />  
                    <input type="button" value="" @click="addCount(item.count,item.id,index)"  class="car_btn_2" />
                </div>
            </td>
            <td align="center" style="color:#ff4e00;">￥{{ countNumber(item.price,"*",item.count) }}</td>
            <td align="center"><a @click="del(item.id)">删除</a>&nbsp; &nbsp;<a @click="clickCollectIcon(item.id)">加入收藏</a></td>
          </tr>
          <tr height="70">
          	<td colspan="6" style="font-family:'Microsoft YaHei'; border-bottom:0;">
            	<!-- <label class="r_rad"><input type="checkbox" name="clear" checked="checked" /></label><label class="r_txt">清空购物车</label> -->
                <span class="fr">商品总价：<b style="font-size:22px; color:#ff4e00;">￥{{ totalPrice }}</b></span>
            </td>
          </tr>
          <tr valign="top" height="150">
          	<td colspan="6" align="right">
            	<router-link to="/goodslist"><img src="../../../assets/images/buy1.gif" /></router-link>&nbsp; &nbsp; <a @click="createOrder" to="/cart-two"><img src="../../../assets/images/buy2.gif" /></a>
            </td>
          </tr>
        </table>
        
    </div>
    </div>
</template>

<script>
import computeNumber from '@/assets/js/computeNumber';
export default {
    name:'CartOne',
    data:function(){
        return{
            allChecked:false,
            isEnough:true,
            oldCounts: [],
            statusArr:[],
        }
    },
    mounted(){
        this.statusArr = new Array(this.$store.state.cartList.length).fill(false);
    },  
    computed:{
        totalPrice(){
            return this.cartList.reduce((sum,item,index)=>{
                if(!this.statusArr[index]){
                    return sum;
                }
                let count = item.count;
                let price = item.price;
                if (!isNaN(price) && !isNaN(count)) {
                    return computeNumber(sum, '+', computeNumber(price, '*', count).result).result;
                }
                return sum;
            },0);
        },
        cartList(){
            return this.$store.state.cartList;
        }
    },
    methods:{
        createOrder(){
            let len = this.statusArr.filter(e=>e===true).length;
            if(len == 0){
                this.$message.error('请选择商品!');
                return;
            }
            //将勾选的商品通过路由传参传递过去
            let goods = this.cartList.reduce((arr,item,index)=>{
                if(this.statusArr[index]){
                    arr.push(item);
                }
                return arr;
            },[]);
            //将商品存到vuex中
            window.sessionStorage.setItem('goods',JSON.stringify(goods));
            this.$store.commit('changeGoods',goods);
            this.$router.push({name:'CartTwo',params:{'goods':goods}});
        },
        selectOne(index){
            this.statusArr[index] = !this.statusArr[index];
            let len = this.statusArr.filter(element => element === true).length;
            if(this.statusArr.length == len){
                this.allChecked = true;
            }else{
                this.allChecked = false;
            }
        },
        selectAll(){
            this.allChecked = !this.allChecked;
            if(this.allChecked){
                this.statusArr.fill(true);
            }else{
                this.statusArr.fill(false);
            }
        },
        addCount(count,productId,index){
            const newCount = count + 1;
            // 修改购物车数量
            // this.$set(this.cartList[index], 'count', newCount); // 保证视图响应
            // this.edit(productId, newCount);
            this.$axios({
                url: '/easybuy/products/getById',
                params: { id: productId }
            }).then(rs => {
                const stock = rs.data.product.stock;
                if (newCount > stock) {
                    this.$message.error('库存数量不足！');
                } else {
                    // 修改购物车数量
                    this.$set(this.cartList[index], 'count', newCount); // 保证视图响应
                    this.edit(productId, newCount);
                }
            });
        },
        reduceCount(count,productId,index){
            if(count ==1){
                this.$message.error('小于最小购买数量！');
                return;
            }
            this.$set(this.cartList[index], 'count', newCount);
            this.edit(productId,count-1);
        },
          // 1. 焦点进入时，缓存旧数量
            cacheOldCount(count, idx) {
                this.$set(this.oldCounts, idx, count);
            },
        //校验商品数量是否正确
        checkNum(id,index){
            //商品数量未发生变化
            const oldCount = this.oldCounts[index];
            const newCount = this.cartList[index].count;

            // 数量没变，直接 return
            if (oldCount === newCount) return;
            let regx = /^[0-9]*[1-9][0-9]*$/;
            if(!regx.test(newCount)){
                this.$message.error('购买商品的数量必须大于0！');
                return;
            }
            //  this.edit(id,newCount);

            // 校验库存是否足够
            this.$axios({
                url:'/easybuy/products/getById',
                params:{
                    id
                }
            }).then(rs=>{
                let stock = rs.data.product.stock;
                let preout = rs.data.product.preout;
                if((stock-preout) < newCount){
                    console.log("库存数量：",rs.data.product.stock,"商品数量：",newCount);
                    this.$message.error('库存数量不足！');
                    this.isEnough = false;
                    this.$set(this.cartList[index], 'count', oldCount);
                }else {
                    this.isEnough = true;
                    if(this.isEnough){
                        //库存数量足够，修改购物车中的数据
                        this.edit(id,newCount);
                    }
                }
            })
          

        },
        //修改购物车信息
        edit(productId,count){
            this.$axios({
                url:'/easybuy/cart/edit',
                params:{
                    productId,
                    count
                }
                }).then(rs=>{
                    //修改vuex中购物车的数据
                     console.log("修改后的购物车：",rs.data);
                    this.$store.commit('changeCartList',rs.data.productVoList);
                     window.sessionStorage.setItem('cartList',JSON.stringify(rs.data.productVoList));
                    this.$message.success('购物车信息修改成功！');
                })
        },
        //从购物车中删除商品
        del(productId){
            this.$confirm('是否将该商品从购物车中删除？','提示',{
                confirmButtonText:'确定',
                cancelButtonText:'取消',
                type:'warning'
            }).then(()=>{
                this.$axios({
                    url:'/easybuy/cart/remove',
                    params:{
                        productId
                    }
                }).then(rs=>{
                    if(rs.data.code == 200){
                       
                        this.$message.success('删除成功！');
                        this.$store.commit('changeCartList',rs.data.productVoList);
                    }else{
                        this.$message.error('删除失败！');
                    }
                })
            }).catch(()=>{
                this.$message.info('已取消删除！');
            })
        },
        //解决精度问题，计算价格
        countNumber(num1,type,num2){
           return computeNumber(num1,type,num2).result;
        },
        //获取收藏夹中的所有商品
        getCollects(){
            this.$axios({
                url:'/easybuy/collect/all',
            }).then(rs=>{
                //将收藏夹中的商品信息存到vuex中
                console.log("collectList:",rs.data.collectList);
                this.$store.commit('changeCollects',rs.data.collectList);
                window.sessionStorage.setItem('collects',JSON.stringify(rs.data.collectList));
            })
        },
        //点击收藏
        clickCollectIcon(productId){
            //判断用户是否登录，如果没登录是不能添加到收藏夹的
            if(!this.$store.state.loginStatus){
                this.$message.error("请先登录");
                return;
            }
            this.$axios({
                url:'/easybuy/collect/add',
                params:{
                    productId
                }
            }).then(rs=>{
                if(rs.data.code == 200){
                     this.isShow = true;
                     this.getCollects();
                }else if(rs.data.code == 5001){
                    this.$message.info("该商品已存在收藏夹中！");
                }else if(rs.data.code == 5002){
                    this.$message.error("最多只能收藏6个商品！");
                }else{
                    this.$message.error("添加失败！");
                }
            })
          
        },
    }
}
</script>

<style>

</style>